/**
 * getSportVenueConfig 响应数据分析
 *  - venueTimeSlotResponses 可以预定的场地时间段
 *  - venuePriceResponses 场地每个时间段的价格
 *  - venueHotBookingTimeResponses 热门时间
 *  - venueResponses 场地列表信息
 */
const axios = require('axios');
const signature = require('./utils/signature');
const handler = require('./utils/handler');

const config = {
    salesItemList: [
        {
            id: 102914,
            name: '简上',
            venues: [
                {
                    number: 24, // 场地号
                    dateTime: [ // 监控的时间
                        {
                            date: '2024-08-01', // 日期
                            time: [ // 时间段
                                '20:00-20:30',
                                '20:30-21:00',
                                '21:00-21:30',
                                '21:30-22:00'
                            ]
                        }
                    ]
                }
            ]
        }
    ],
    taskRunTime: {
        min: (60 * 1000),
        max: (5 * 60 * 1000)
    }
};

const venueInfoList = async (salesItem, date, timestamp) => {
    let getSportVenueConfig = `https://isz.ydmap.cn/srv100352/api/pub/sport/venue/getSportVenueConfig?salesItemId=${salesItem.id}&curDate=${date.day}&venueGroupId=&t=${timestamp}`;
    let getVenueOrderList = `https://isz.ydmap.cn/srv100352/api/pub/sport/venue/getVenueOrderList?salesItemId=${salesItem.id}&curDate=${date.day}&venueGroupId=&t=${timestamp}`;

    let getSportVenueConfigReq = axios.get(getSportVenueConfig, {headers: signature(getSportVenueConfig)});
    let getVenueOrderListReq = axios.get(getVenueOrderList, {headers: signature(getVenueOrderList)});

    let responses = await Promise.all([getSportVenueConfigReq, getVenueOrderListReq]);
    if (responses[0].data.code === 0 && responses[1].data.code === 0) {
        handler(salesItem, date, responses[0].data.data, responses[1].data.data);
    } else {
        console.log('Promise.all err', responses.data);
    }
};

const venueCalendarList = async () => {
    let timestamp = new Date().getTime();

    for (let salesItem of config.salesItemList) {
        let url = `https://isz.ydmap.cn/srv100352/api/pub/sport/venue/getVenueCalendarList?salesItemId=${salesItem.id}&t=${timestamp}`;
        let sign = signature(url);
        let response = await axios.get(url, {headers: {...sign}});

        if (response.data.code === 0) {
            let freeDateList = response.data.data.map(obj => `${obj.dayName}(${obj.weekName})`);
            console.log(`[${salesItem.name}] 当前可以预定的日期是: ${freeDateList.join(', ')}`);

            for (let date of response.data.data) {
                await venueInfoList(salesItem, date, timestamp);
            }
        } else {
            console.error(`获取'${salesItem.name}'场地可定日期列表错误`, response);
        }
    }
};

const run = () => {

    const getRandomNumber = (min, max) => {
        return Math.floor(Math.random() * (max - min + 1) + min);
    };

    const formatDateTime = (time) => {
        if (time >= (60 * 1000)) {
            let totalSeconds = Math.floor(time / 1000);
            let minutes = Math.floor(totalSeconds / 60);
            let seconds = totalSeconds % 60;
            return `${minutes}分${seconds}秒`;
        } else if (time >= 1000) {
            return `${(time / 1000).toFixed(2)}秒`;
        } else {
            return `${time}毫秒`;
        }
    };

    venueCalendarList().then(() => {
        let number = getRandomNumber(config.taskRunTime.min, config.taskRunTime.max);

        setTimeout(run, number);

        console.log(`运行成功, 下一次任务运行等待时长 --> ${formatDateTime(number)}`);
    }).catch(err => {
        console.error('运行失败', err);
    });
};

run();